using System.Collections.Generic;
using System.Linq;
using UnityEngine;
//用于存储物品数据库
[CreateAssetMenu(menuName = "库存系统/物品数据库")]
public class Database : ScriptableObject
{
    [SerializeField] private List<InventoryItemData> _itemDatabase;

    [ContextMenu(itemName: "设置IDs")]
    public void SetItemIDs()
    {
        _itemDatabase = new List<InventoryItemData>();

        // 从Resources文件夹中加载所有的InventoryItemData资源，并按照ID进行排序
        var foundItems = Resources.LoadAll<InventoryItemData>("ItemData").OrderBy(i => i.ID).ToList();

        // 根据物品的ID范围将物品分为不同的列表
        var hasIDInRange = foundItems.Where(i => i.ID != -1 && i.ID < foundItems.Count).OrderBy(i => i.ID).ToList();
        var hasIDNotInRange = foundItems.Where(i => i.ID != -1 && i.ID > foundItems.Count).OrderBy(i => i.ID).ToList();
        var noID = foundItems.Where(i => i.ID <= -1).ToList();

        var index = 0;
        
        for (int i = 0; i < foundItems.Count; i++)
        {
            InventoryItemData itemToAdd;

            itemToAdd = hasIDInRange.Find(d => d.ID == i);

            if (itemToAdd != null)
            {
                _itemDatabase.Add(itemToAdd);
            }
            else if (index < noID.Count)
            {
                noID[index].ID = i;
                itemToAdd = noID[index];
                index++;
                _itemDatabase.Add(itemToAdd);
            }
        }

        foreach (var item in hasIDNotInRange)
        {
            _itemDatabase.Add(item);
        }
    }

    // 根据给定的ID从物品数据库中查找并返回对应的物品数据
    public InventoryItemData GetItem(int id)
    {
        return _itemDatabase.Find(i => i.ID == id);
    }
}
